import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';

import Apis from '../apis';
import { User } from '../models/user';

function auth() {
  const subject = new BehaviorSubject<User | undefined>(undefined);

  const asyncUserInfo = subject.pipe(
    map(($user) => ({
      authenticated: $user !== null && $user !== undefined,
      user: $user,
    }))
  );

  const login = (username: string, password: string) =>
    Apis.User.login(username, password).then((user) => subject.next(user));

  const load = () => Apis.User.load().then((user) => subject.next(user));

  const logout = () => Apis.User.logout().then(() => subject.next(undefined));

  return {
    user: asyncUserInfo,
    login,
    logout,
    load,
  };
}

export default auth();
